package com.zhou.service.impl;

import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zhou.entity.Oss;
import com.zhou.mapper.OssMapper;
import com.zhou.service.OssService;
import com.zhou.utils.OssUtil;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description : 阿里云文件上传
 * @Author : zyy
 * @Date: 2024/6/12  14:38
 */
@Slf4j
@Service
public class OssServiceImpl implements OssService {
    @Autowired
    private OssMapper ossMapper;

    @Override
    public String upload(MultipartFile file) {
        //oss 上传图片
        //先将oss的相关信息获取出来
        String url = null;
        String endPoint = OssUtil.END_POINT;
        String accessKeyId = OssUtil.ACCESS_KEY_ID;
        String accessKeySecret = OssUtil.ACCESS_KEY_SECRET;
        String bucketName = OssUtil.BUCKET_NAME;
        OSS build = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = file.getInputStream();
            //获取文件上传的文件名
            String originalFilename = file.getOriginalFilename();
            //随机uuid为了拼接文件名，防止用户上传两个相同的文件名覆盖掉
            UUID uuid = UUID.randomUUID();
            //这是为了加时间分配目录
            String string = DateTime.now().toString("yyyy/MM/");
            //拼接字符串
            String fileName = string + uuid + originalFilename;
            //传入参数
            build.putObject(bucketName,fileName,inputStream);
            //拼接路径存入数据库
            url = "https://" + bucketName + "." + endPoint + "/" + fileName;
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            build.shutdown();
        }
        Oss oss =new Oss();
        oss.setUrl(url);
        oss.setOssId(UUID.randomUUID().toString());
        int insert = ossMapper.insert(oss);
        log.info("插入结果",insert ==0?"失败":"成功");
        return url;
    }
}
